package com.dt.common.validation.parser;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dt.common.validation.annotation.Option;
import com.dt.common.validation.definition.OptionDefinition;
import com.dt.common.validation.exception.BuildingException;
import com.dt.common.validation.impl.DefaultValidationDefinition;
import com.dt.common.validation.itf.PropertyGetter;

public class OptionDefinitionParser extends DefinitionParser {

	@Override
	public DefaultValidationDefinition parseFromAnnotation(Field field, PropertyGetter propertyGetter) {
		Option option = field.getAnnotation(Option.class);
		if (option != null) {
			String[] valuesArray = option.values();
			if (valuesArray == null || valuesArray.length == 0) {
				throw new BuildingException("Option values must has value.");
			}
			String msg = option.msg();

			return build(Arrays.asList(valuesArray), msg);
		}
		return null;
	}

	private OptionDefinition build(List<String> values, String msg) {
		OptionDefinition definition = new OptionDefinition();
		definition.setValues(values);
		definition.setRawMsg(msg);
		return definition;
	}

	@Override
	public DefaultValidationDefinition parseFromJson(JSONObject metaValues) {
		JSONArray valueArray = metaValues.getJSONArray("values");
		if (valueArray == null || valueArray.isEmpty()) {
			throw new BuildingException("Option values must define.");
		}
		List<String> values = new ArrayList<>();
		for (int i = 0; i < valueArray.size(); ++i) {
			String value = valueArray.getString(i);
			values.add(value);
		}
		if (values.size() == 0) {
			throw new BuildingException("Option values must has value.");
		}

		String msg = this.getMsgDefinition(metaValues, true);

		return build(values, msg);
	}

}
